﻿#include "textedit.h"

TextEdit::TextEdit(QWidget *parent): QTextEdit(parent) {

}
bool TextEdit::canInsertFromMimeData(const QMimeData *source) const
{
    return source->hasImage() || source->hasUrls() ||
           QTextEdit::canInsertFromMimeData(source);
}

void TextEdit::insertFromMimeData(const QMimeData *source){
    if (source->hasUrls()) {
        foreach (QUrl url, source->urls()) {
            insertFile(url.toLocalFile());
        }
    }
    else {
        QTextEdit::insertFromMimeData(source);
    }

}

void TextEdit::mousePressEvent(QMouseEvent *event) {
    QTextCursor cursor = cursorForPosition(event->pos());

    return QTextEdit::mousePressEvent(event);
}

void TextEdit::mouseDoubleClickEvent(QMouseEvent *event) {

    QTextCursor cursor = cursorForPosition(event->pos());
    QTextBlock block =cursor.block();

    int site=cursor.position();
    if (block.isValid() && !cursor.atEnd())
    {
        if(!cursor.atStart())
        {
            QChar preChar = block.text().at(site - 1);
            QChar curChar = block.text().at(site);
            // 判断是否点击到单词内部或单词边界（包括空格到字母的转换）
            if ((preChar.isLetterOrNumber() && curChar.isLetterOrNumber()) ||
                (preChar.isSpace() && curChar.isLetterOrNumber()))
            {
                // 向前移动到单词开始
                while (!cursor.atStart())
                {
                    QChar pre = block.text().at(cursor.position() - 1);
                    if (pre.isSpace() || !pre.isLetterOrNumber())
                        break;
                    cursor.movePosition(QTextCursor::PreviousCharacter);
                }
                int wordStart = cursor.position();// 保存单词开始位置
                cursor.setPosition(site);// 恢复初始位置
                while (!cursor.atEnd())// 向后移动到单词结束
                {
                    QChar cur = cursor.block().text().at(cursor.position());
                    if (cur.isSpace() || !cur.isLetterOrNumber())
                        break;
                    cursor.movePosition(QTextCursor::NextCharacter);
                }
                cursor.setPosition(wordStart, QTextCursor::KeepAnchor);// 设置选择范围并显示选中内容
                setTextCursor(cursor); // 确保这个函数或方法能够设置QTextEdit或其他QTextDocument的文本光标
            }
            else
            {
                cursor.movePosition(QTextCursor::NextCharacter);
                cursor.setPosition(site, QTextCursor::KeepAnchor);
                setTextCursor(cursor);
            }
        }
        else
        {
            cursor.movePosition(QTextCursor::NextCharacter);
            cursor.setPosition(site, QTextCursor::KeepAnchor);
            setTextCursor(cursor);
        }
    }
}
void TextEdit::insertFile(const QString &filePath){
    QFileInfo fileInfo(filePath);
    if(fileInfo.exists()&&fileInfo.size()>0){
        QSize targetSize=scaleImageSize(filePath);
        if(!targetSize.isNull()){// 插入图片并设置其大小
            QTextImageFormat imageFormat;
            imageFormat.setName(filePath);
            imageFormat.setWidth(targetSize.width());
            imageFormat.setHeight(targetSize.height());
            // 获取文本光标并插入图片
            QTextCursor cursor = textCursor();
            cursor.beginEditBlock();
            cursor.insertImage(imageFormat);
            cursor.endEditBlock();
        }
    }
}

QSize TextEdit::scaleImageSize(const QString &imagePath){//缩放图片到适合的大小
    QPixmap pixmap(imagePath);
    if (pixmap.isNull()) {
        emit upLoadFile(imagePath);//上传文件
        return QSize(0,0);
    }
    //按比例缩放图片
    //Qt::KeepAspectRatio保持长宽比
    //Qt::FastTransformation快速转换，提高处理速度，不考虑质量
    pixmap = pixmap.scaled(150, 150, Qt::KeepAspectRatio, Qt::FastTransformation);
    //设置最小的显示图片宽度为68
    if(pixmap.width()<68){
        pixmap=pixmap.scaledToWidth(68,Qt::FastTransformation);
        if(pixmap.height()>150){
            return QSize(68,150);
        }
    }
    //设置最小的显示图片高度为68
    if(pixmap.height()<68){
        pixmap=pixmap.scaledToHeight(68, Qt::FastTransformation);
        if(pixmap.width()>150){
            return QSize(150,68);
        }
    }
    return pixmap.size();
}

void TextEdit::dropTextFile(const QUrl &url)
{
    QFile file(url.toLocalFile());
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
        textCursor().insertText(file.readAll());
}

